package com.zaicheng.cloud.loadbanlancer.server.impl;
/**
 @author zaicheng
 @version 1.0
 @date 2022-04-19
 @email zzc15847256473@163.com
 */

//import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.zaicheng.cloud.loadbanlancer.server.ServerList;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NacosServerList implements ServerList<NacosServer> {

//    private NacosDiscoveryProperties discoveryProperties;

    private String serviceId;

    private NamingService namingService;

//    public NacosServerList(NacosDiscoveryProperties discoveryProperties) {
//        this.discoveryProperties = discoveryProperties;
//    }

    public NacosServerList(NamingService namingService) {
        this.namingService = namingService;
    }

    @Override
    public List<NacosServer> getUpdatedListOfServers() {
        return this.getServers();
    }

    private  List<NacosServer>  getServers(){
        try {
            //String group = this.discoveryProperties.getGroup();
            //List<Instance> instanceList = this.discoveryProperties.namingServiceInstance().selectInstances(this.serviceId, group, true);
            List<Instance> instanceList = this.namingService.selectInstances("order-service","DEFAULT_GROUP",true);
            return this.instancesToServerList(instanceList);
        }catch (Exception e){
            e.printStackTrace();
            throw new IllegalStateException("不能从nacos获取到服务实例信息");
        }
    }

    private  List<NacosServer>  instancesToServerList(List<Instance> instances){
        List<NacosServer> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(instances)){
            return result;
        }else{

            Iterator<Instance> iterator = instances.iterator();

            while (iterator.hasNext()){
                Instance instance = iterator.next();
                result.add(new NacosServer(instance));
            }
            return result;
        }
    }


}
